package cn.ycbjie.ycaudioplayer.newpack.linkagescroll.adapter;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;


import com.synjones.minnovate.frame.basesdk.http.SynHttp;
import com.synjones.minnovate.frame.basesdk.http.SynSchedulersTranfs;
import com.synjones.minnovate.frame.basesdk.http.exception.AbsRxSubscriber;
import com.synjones.minnovate.frame.basesdk.http.exception.ApiException;
import com.synjones.minnovate.frame.basesdk.log.SynLog;

import java.util.List;

import cn.ycbjie.ycaudioplayer.R;
import cn.ycbjie.ycaudioplayer.mybean.mycontent;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.holder.RecyclerItemViewHolder;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.iapiserver.iapi;
import cn.ycbjie.ycaudioplayer.newpack.linkagescroll.model.RecyclerDataModel;

import static cn.ycbjie.ycaudioplayer.newpack.linkagescroll.config.MyConfig.baseURL;


/**
 * Created by GUO on 2015/12/3.
 */

/**
 * Created by Nelson on 15/11/9.
 */
public class RecyclerBaseAdapter2 extends RecyclerView.Adapter {

    private final static String TAG = "RecyclerBaseAdapter";

    private List<mycontent> itemDataList = null;
    private Context context = null;
    private boolean mIsLoading;
    WebView web;
    public RecyclerBaseAdapter2(Context context, List<mycontent> itemDataList) {
        this.itemDataList = itemDataList;
        this.context = context;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                      int viewType) {
        View v = LayoutInflater.from(context).inflate(R.layout.list_item_layout2, parent, false);
        final RecyclerView.ViewHolder holder = new RecyclerItemViewHolder(context, v);
        web = (WebView)v.findViewById(R.id.web);

        WebSettings settings = web.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        web.setWebViewClient(new MyWebViewClient());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
        } else {
            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        }
        if (web.isHardwareAccelerated()) settings.setJavaScriptEnabled(true);
//        webView.setWebViewClient(new WebViewClient());
//        webView.setWebChromeClient(new WebChromeClient());
//        WebSettings settings = webView.getSettings();
//        settings.setJavaScriptEnabled(true);
//        webView.loadUrl("https://www.jianshu.com/c/fcd7a62be697?utm_source=mobile&utm_medium=collections");


//        webView = (WebView)v.findViewById(R.id.web);
//
//        WebSettings webSettings = webView.getSettings();
////支持缩放，默认为true。
//        webSettings .setSupportZoom(false);
////调整图片至适合webview的大小
//        webSettings .setUseWideViewPort(true);
//// 缩放至屏幕的大小
//        webSettings .setLoadWithOverviewMode(true);
////设置默认编码
//        webSettings .setDefaultTextEncodingName("utf-8");
//////设置自动加载图片
//        webSettings .setLoadsImagesAutomatically(true);
//        webView.loadUrl("https://www.jianshu.com/c/fcd7a62be697?utm_source=mobile&utm_medium=collections");
        return holder;

    }
    private String getHtmlData(String bodyHTML) {
        String head = "<head>" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
                "<style>html{padding:15px;} body{word-wrap:break-word;font-size:13px;padding:0px;margin:0px} p{padding:0px;margin:0px;font-size:13px;color:#222222;line-height:1.3;} img{padding:0px,margin:0px;max-width:100%; width:auto; height:auto;}</style>" +
                "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        web.loadData(getHtmlData(itemDataList.get(0).getData().getContent()), "text/html;charset=utf-8", "utf-8");
//holder.web.
    }

    @Override
    public int getItemCount() {
       return itemDataList.size();
    }


    @Override
    public int getItemViewType(int position) {
        return 1;
    }

    public void setListData(List<mycontent> data) {
        itemDataList = data;
        notifyDataSetChanged();
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //判断重定向的方式一
//            WebView.HitTestResult hitTestResult = view.getHitTestResult();
//            if(hitTestResult == null) {
//                return false;
//            }
//            if(hitTestResult.getType() == WebView.HitTestResult.UNKNOWN_TYPE) {
//                return false;
//            }

            //判断重定向的方式二
            if(mIsLoading) {
                return false;
            }

            if(url != null && url.startsWith("http")) {
                web.loadUrl(url);
                return true;
            } else {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                try {
                    view.getContext().startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    e.printStackTrace();
                }
                return true;
            }
        }


        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mIsLoading = true;
            Log.d(TAG, "onPageStarted");
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mIsLoading = false;
            Log.d(TAG, "onPageFinished");
        }

//        @Override
//        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
//            super.onReceivedError(view, request, error);
//        }
    }

    private class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            return super.onJsAlert(view, url, message, result);
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            return super.onJsConfirm(view, url, message, result);
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            return super.onJsPrompt(view, url, message, defaultValue, result);
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            return super.onShowFileChooser(webView, filePathCallback, fileChooserParams);
        }
    }

}
